package com.sanpu.kxe.business.main.presenter;

import android.app.Activity;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.sanpu.library.imagechoose.PhotoPreview;
import com.sanpu.kxe.business.main.bean.PromotePosterOutput;
import com.sanpu.kxe.business.main.bean.ShareNumOutput;
import com.sanpu.kxe.business.main.contract.PromotePosterContract;
import com.sanpu.kxe.business.main.interfaces.IOnPromoteClickListener;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.jump.shareutil.ShareUtil;
import com.sanpu.kxe.jump.shareutil.share.ShareListener;
import com.sanpu.kxe.jump.shareutil.share.SharePlatform;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.ToastUtil;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * Description：推广海报
 * Created by 薛勇军 on 2018/8/20.
 */

public class PromotePosterPresenter implements PromotePosterContract.Presenter {

    private PromotePosterContract.View mView;

    private CompositeSubscription mSubscription;

    private String filePath;

    private IWXAPI msgApi;

    public PromotePosterPresenter(PromotePosterContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void getPosterList(final int nowPage) {
        Subscription subscription = MainModel.getInstance().getPosterList(nowPage)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<PromotePosterOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                        mView.showLoadMore(CommonConfig.LOADMOREFAIL);
                    }

                    @Override
                    public void onNext(List<PromotePosterOutput> promotePosterOutputs) {
                        if (promotePosterOutputs != null) {
                            mView.showPromoteListView(promotePosterOutputs, nowPage == 0);
                            if (promotePosterOutputs.size() < CommonConfig.PAGENUMER) {
                                mView.showLoadMore(CommonConfig.LOADMOREEND);
                            } else {
                                mView.showLoadMore(CommonConfig.LOADMORECOMPLETE);
                            }
                        } else {
                            mView.showLoadMore(CommonConfig.LOADMOREEND);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 海报分享次数
     */
    private void addShareNum(final String posterId, final int position) {
        Subscription subscription = MainModel.getInstance().addShareNum(posterId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ShareNumOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("materialDNum", "调用海报分享次数接口失败");
                    }

                    @Override
                    public void onNext(ShareNumOutput shareNumOutput) {
                        if (shareNumOutput != null && !TextUtils.isEmpty(shareNumOutput.getShareNum())) {
                            mView.setNotify(position, shareNumOutput.getShareNum());
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public IOnPromoteClickListener getPromoteClickListener() {
        return new IOnPromoteClickListener() {
            @Override
            public void onClick(ArrayList<String> datas, int position) {
                if (datas == null || datas.isEmpty()) return;
                for (int i = 0; i < datas.size(); i++) {
                    datas.set(i, UrlConstants.getBaseUrl() + datas.get(i));
                }
                PhotoPreview.builder()
                        .setPhotos(datas)
                        .setCurrentItem(position)
                        .setShowDeleteButton(false)
                        .start((Activity) mView.getContext());
            }

            @Override
            public void onSave(List<String> datas, String title, String mltId, int position) {
                if (datas != null && !datas.isEmpty()) {
                    mView.showLoadingDialog(false, "分享中...");
                    addShareNum(mltId, position);
//                    saveImages(datas, title);
                    shareWx(datas, title);
                }
            }

            @Override
            public void onCopy(String title) {
                if (android.os.Build.VERSION.SDK_INT > 11) {
                    android.content.ClipboardManager c = (android.content.ClipboardManager)
                            mView.getContext().getSystemService(CLIPBOARD_SERVICE);
                    c.setPrimaryClip(ClipData.newPlainText("txt", title));
                } else {
                    android.text.ClipboardManager c = (android.text.ClipboardManager)
                            mView.getContext().getSystemService(CLIPBOARD_SERVICE);
                    c.setText(title);
                }
                ToastUtil.showTextViewPrompt(mView.getContext(), "复制文案成功");
            }
        };
    }

    /**
     * 分享到朋友圈
     */
    private void shareWx(List<String> datas, String title) {
        if (!isWXAppInstalledAndSupported()) {
            ToastUtil.showTextViewPrompt("未安装微信");
            return;
        }
        if (datas != null && !datas.isEmpty() && !TextUtils.isEmpty(datas.get(0))) {
            final String shareUrl = UrlConstants.getBaseUrl() + datas.get(0);
            if (android.os.Build.VERSION.SDK_INT > 11) {
                android.content.ClipboardManager c = (android.content.ClipboardManager)
                        mView.getContext().getSystemService(CLIPBOARD_SERVICE);
                c.setPrimaryClip(ClipData.newPlainText("txt", title));
            } else {
                android.text.ClipboardManager c = (android.text.ClipboardManager)
                        mView.getContext().getSystemService(CLIPBOARD_SERVICE);
                c.setText(title);
            }
            DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mView.getContext(),
                    "文案内容已复制，请长按粘贴后发布朋友圈", "取消", "转发",
                    new DialogViewListener() {
                        @Override
                        public void btnRightConfirm() {
                            ShareListener shareListener = new ShareListener() {
                                @Override
                                public void shareSuccess() {
                                    mView.dismissLoadingDialog();
                                }

                                @Override
                                public void shareFailure(Exception e) {
                                    ToastUtil.showTextViewPrompt("分享失败");
                                    mView.dismissLoadingDialog();
                                }

                                @Override
                                public void shareCancel() {
                                    mView.dismissLoadingDialog();
                                }
                            };
                            ShareUtil.shareImage(mView.getContext(), SharePlatform.WX_TIMELINE, shareUrl, shareListener);
                        }

                        @Override
                        public void btnLeftCancel() {
                            mView.dismissLoadingDialog();
                        }
                    });
        } else {
            ToastUtil.showTextViewPrompt("分享内容不存在！");
            mView.dismissLoadingDialog();
        }
    }

    /**
     * 本机是否支持微信支付
     */
    public boolean isWXAppInstalledAndSupported() {
        msgApi = WXAPIFactory.createWXAPI(mView.getContext(), null);
        msgApi.registerApp(CommonConfig.WX_APPID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    /**
     * 保存图片用于分享
     */
    private void saveImages(final List<String> datas, final String title) {
        new Thread() {
            public void run() {
                for (String imageUrl : datas) {
                    URL url;
                    HttpURLConnection connection = null;
                    Bitmap bitmap = null;
                    InputStream inputStream = null;
                    try {
                        url = new URL(UrlConstants.getBaseUrl() + imageUrl);
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(6000); //超时设置
                        connection.setDoInput(true);
                        connection.setUseCaches(false); //设置不使用缓存
                        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            inputStream = connection.getInputStream();
                            bitmap = BitmapFactory.decodeStream(inputStream);
                            String fileName = "material_" + System.currentTimeMillis() + ".png";
                            FileUtil.saveFileToBitmap(mView.getContext(), bitmap, filePath, fileName);
                        }
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Message message = new Message();
                message.what = 0x123;
                message.obj = title;
                handler.sendMessage(message);
            }
        }.start();
    }

    /**
     * 下载图片回调
     */
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0x123) {
                mView.dismissLoadingDialog();
                share(msg.obj + "");
            }
        }
    };

    /**
     * 分享到朋友圈（多图片带文字）
     */
    private void share(String title) {
        try {
            List<String> files = FileUtil.getImagePathFromSD(filePath);
            Intent intent = new Intent();
            ComponentName comp = new ComponentName("com.tencent.mm",
                    "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setType("image/*");
            ArrayList<Uri> imageUris = new ArrayList<Uri>();
            for (String f : files) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    File file = new File(f);
                    Uri uri =Uri.parse(MediaStore.Images.Media.insertImage(
                            mView.getContext().getContentResolver(), file.getAbsolutePath(), file.getName(), null));
                    imageUris.add(uri);
                } else {
                    imageUris.add(Uri.fromFile(new File(f)));
                }
            }
            if (imageUris.size() > 1) {
                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
            } else if (imageUris.size() == 1) {
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, imageUris.get(0)); //图片数据（支持本地图片的Uri形式）
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("Kdescription", title);
            IntentTool.startActivityForResult(mView.getContext(), intent, CommonConfig.REQUESTCODE_PROMOTE_POSTER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
